package com.azdebugit.hash.map.test.util;

import com.google.common.base.CaseFormat;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;

public class MapFormatUtils {
    private static final Logger log = LoggerFactory.getLogger(MapFormatUtils.class);

    public MapFormatUtils() {
    }

    public static Map formatHumpName(Map map) {
        if (CollectionUtils.isEmpty(map)) {
            return null;
        } else {
            Map newMap = new HashMap();
            map.forEach((k, v) -> {
                newMap.put(toFormatCol(k.toString()), v);
            });
            return newMap;
        }
    }

    public static String toFormatCol(String colName) {
        return CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, colName);
    }

    public static List<Map> formatHumpNameForList(List<Map> list) {
        if (CollectionUtils.isEmpty(list)) {
            return null;
        } else {
            List<Map> newList = new ArrayList();
            Iterator ite = list.iterator();

            while(ite.hasNext()) {
                Map o = (Map)ite.next();
                newList.add(formatHumpName(o));
            }

            return newList;
        }
    }

    public static Object convertMapToJavaBean(Class<?> clazz, Map<String, Object> params) {
        Object obj = null;

        try {
            BeanInfo beanInfo = Introspector.getBeanInfo(clazz);
            obj = clazz.newInstance();
            PropertyDescriptor[] pro = beanInfo.getPropertyDescriptors();
            PropertyDescriptor[] newPro = pro;
            int proSize = pro.length;

            for(int i = 0; i < proSize; ++i) {
                PropertyDescriptor propertyDescriptor = newPro[i];
                String propertyName = propertyDescriptor.getName();
                if (params.containsKey(propertyName)) {
                    Object value = params.get(propertyName);
                    if ("".equals(value)) {
                        value = null;
                    }

                    Object[] args = new Object[]{value};
                    propertyDescriptor.getWriteMethod().invoke(obj, args);
                }
            }
        } catch (Exception e) {
            log.error("map转换异常", e);
        }

        return obj;
    }
}